import fileDownload from 'js-file-download'
import useWait from '../useAwait'
/**
 * @title 静态资源相关的操作工具
 */
function useResourceHelper(params: { baseUrl: string } = { baseUrl: '/api' }) {
    const { baseUrl } = params

    function getStaticUrl(path: string) {
        if(path.startsWith('/api/download/')){
            return path
        }else{
            return `${baseUrl}/download/${path}`
        }

    }

    function downloadFile(url: string, filename: string) {
        const link = document.createElement('a')
        link.href = url
        link.download = filename
        link.target = '_blank'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    }

    function downloadAndRenameFile(filename: string) {
        
        const path = getStaticUrl(filename)

        downloadFile(path, filename)
    }

    function downloadStringAsText(content: string, name: string) {
        fileDownload(content, name)
    }

    function downloadBase64AsImg(base64Str:string){

        const a = document.createElement('a');

        a.href = base64Str;

        a.download = 'screenshot.png';

        // 模拟点击链接以触发下载
        a.click();

        useWait(300).then(()=>{
            document.body.removeChild
        })
    }

    function replaceDiskHeader(content: string) {
        // const disk_header_reg = /^([A-Z]):(\\||\/\/)zs\\dtjc_test_data\\test/
        const disk_header_reg = GLOBAL_REPLACE_TIF_HEADER_REGEX

        const scp_header = '$[SCP_SHARE]\\'

        const replaced_path_1 = content.replace(disk_header_reg, scp_header)
        console.log('replaced_path_1', replaced_path_1)
        // const replaced_path_2= replaced_path_1.replace('/dtjc_test_data\\test', '')
        // console.log('replaced_path_2', replaced_path_2)

        return replaced_path_1
    }

    function replaceHeader(content:string){
        const disk_header_reg = GLOBAL_REPLACE_OVERLAY_HEADER_REGEX
        const replaced_path_1 = content.replace(disk_header_reg, '')

        return replaced_path_1
    }

    

    return {
        getStaticUrl,
        downloadFile,
        downloadAndRenameFile,
        downloadStringAsText,
        downloadBase64AsImg,
        replaceDiskHeader,
        replaceHeader,
    }
}

export default useResourceHelper
